#!/usr/bin/env bash

[ $UID -ne 0 ] && echo "This program must be run as root!" && exit 1

URL="https://www.python.org/ftp/python/2.7.8"
BACKUP_DATE=`date +%F-%H%M%S`

message() {
    printf '%b\n' "$1" >&2
}

notice() {
    echo -e " \033[1;33m$@\033[0m";
}

failure() {
    echo -e " \033[1;31m[Error]\033[0m  $@";  exit 1;
}

success() {
    [ "$?" -eq '0' ] && message "\33[32m[OK]\33[0m ${1}${2}"
}

help_info() {
    cat << EOF
    usage: $0 [OPTIONS]

    help                            show this information
    install                         install all tools
    fix                             recomile python
    book                            initialize a book
EOF
}

detect_plat() {
    which python > /dev/null 2>&1
    if [[ $? -eq 0 ]]; then
        python << EOF
import platform
dist = platform.dist()[0]
version = platform.dist()[1]
f = open('dist', 'w')
f.write(dist + ' ' + version)
f.close()
EOF
        DIST=`cat dist | cut -d' ' -f1 | awk '{print tolower($0)}'`
        VERSION=`cat dist | cut -d' ' -f2`
        MAJOR=`echo $VERSION | cut -d. -f1`
        MINOR=`echo $VERSION | cut -d. -f2`
        ARCH=$(uname -m)
        rm dist -rf
    else
        failure "Detect platform failed, can not continue."
    fi
}

sources() {
    if [[ "$DIST" = "ubuntu" ]]; then
        if [[ "$1" = "update" ]]; then
            mirror="http://mirrors.163.com/.help"
            mv /etc/apt/sources.list /etc/apt/sources.list.bak
            if [[ $MAJOR = "12" ]]; then
                wget $mirror/sources.list.precise && mv sources.list.precise /etc/apt/sources.list
            elif [[ $MAJOR = "14" ]]; then
                wget $mirror/sources.list.trusty && mv sources.list.trusty /etc/apt/sources.list
            else
                failure "Unsupport $DIST$VERSION"
            fi
            apt-get update
        elif [[ "$1" = "restore" ]]; then
            mv /etc/apt/sources.list.bak /etc/apt/sources.list
        fi
    elif [[ "$DIST" = "debian" ]]; then
        if [[ "$1" = "update" ]]; then
            mirror="http://mirrors.163.com/.help"
            mv /etc/apt/sources.list /etc/apt/sources.list.bak
            if [[ $MAJOR = "6" ]]; then
                wget $mirror/sources.list.squeeze && mv sources.list.squeeze /etc/apt/sources.list
            elif [[ $MAJOR = "7" ]]; then
                wget $mirror/sources.list.wheezy && mv sources.list.wheezy /etc/apt/sources.list
            elif [[ $MAJOR = "8" ]]; then
                wget $mirror/sources.list.jessie && mv sources.list.jessie /etc/apt/sources.list
            else
                failure "Unsupport $DIST$VERSION"
            fi
            apt-get update
        elif [[ "$1" = "restore" ]]; then
            mv /etc/apt/sources.list.bak /etc/apt/sources.list
        fi
    elif [[ "$DIST" = "centos" ]]; then
        if [[ "$1" = "update" ]]; then
            > /dev/null
        elif [[ "$1" = "restore" ]]; then
            > /dev/null
        fi
    elif [[ "$DIST" = "redhat" ]]; then
        if [[ "$1" = "update" ]]; then
            > /dev/null
        elif [[ "$1" = "restore" ]]; then
            > /dev/null
        fi
    fi
}

prepare() {
    sources "update"
    if [[ "$DIST" = "ubuntu" || "$DIST" = "debian" ]]; then
        PM=apt
        $PM install -y g++ \
            bison \
            make \
            bzip2 \
            libbz2-dev \
            openssl \
            libssl-dev
    elif [[ "$DIST" = "centos" || "$DIST" = "redhat" ]]; then
        PM=yum
        $PM install -y gcc-c++ \
            bison \
            make \
            bzip2 \
            bzip2-devel \
            openssl \
            openssl-devel
    else
        failure "Unsupport $DIST"
    fi
}

install_node() {
    wget https://nodejs.org/dist/v0.10.4/node-v0.10.4.tar.gz ||
        failure "Download nodejs failed, can not continue."
    tar -xvf node-v0.10.4.tar.gz
    cd node-v0.10.4 &&
        ./configure &&
        make &&
        make install &&
        cd .. &&
        rm node-v0.10.4* -rf ||
        failure "Install nodejs failed, can not continue."
}

install_npm() {
    wget https://registry.npmjs.org/npm/-/npm-4.1.2.tgz ||
        failure "Download npm failed, can not continue."
    tar -xvf npm-4.1.2.tgz
    cd package &&
        ./configure &&
        make all &&
        make install &&
        cd .. &&
        rm npm-4.1.2* -rf ||
        failure "Install npm failed, can not continue."
}

recompile_python() {
    python_path="/usr/local"
    test -n $URL && wget $URL/Python-2.7.8.tgz || failure "Python-2.7.8.tgz not found, can not continue."
    tar xvf Python-2.7.8.tgz &&
        cd Python-2.7.8 &&
        ./configure --prefix=$python_path/python2.7 --enable-shared &&
        make &&
        make install &&
        cd .. && rm Python-2.7.8* -rf ||
        failure "Install Python-2.7.8 failed, can not continue."

    mv /usr/bin/python /usr/bin/python.${BACKUP_DATE}.bak 2>&1 > /dev/null
    ln -s $python_path/python2.7/bin/python2.7 /usr/bin/python
    ln -s $python_path/python2.7/lib/libpython2.7.so.1.0 /usr/local/lib
    test -e /usr/local/lib/libpython2.7.so && rm /usr/local/lib/libpython2.7.so
    ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/local/lib/libpython2.7.so
    echo "/usr/local/lib" >> /etc/ld.so.conf
    ldconfig
}

detect_plat

case "$1" in
    -h|--help|help )
        help_info
        ;;
    install )
        prepare
        install_node
        install_npm
        which npm > /dev/null 2>&1 || failure "npm is not in PATH, check your env please."
        npm cache clean -f
        npm install -g n
        n stable
        npm install -g loppo
        ;;
    fix )
        recompile_python
        ;;
    book )
        test -n "$2" || failure "Book title can not be blank"
        mkdir -p "$2"/docs
        touch "$2"/READ.md
        touch "$2"/docs/page1.md
        ;;
    * )
        echo "Unkown option [$1]"
        help_info
        exit 1
        ;;
esac
